<template>
  <view class="confirm-order-container">

    <!-- 收货地址部分 -->
    <view class="address-section" @click="goToAddressPage">
      <text class="section-title">收货地址</text>
      <view v-if="selectedAddress" class="address-info">
        <text>{{ selectedAddress.city }} {{ selectedAddress.department }} {{ selectedAddress.houseNumber }}</text>
        <image class="edit-icon" src="/static/编辑.png" mode="aspectFit" ></image>
        <text>{{ selectedAddress.name }} {{ selectedAddress.phone }}</text>
         
      </view>
      
    </view>

    <!-- 商品列表部分（按超市分组） -->
    <view class="product-section">
      <view v-for="(products, storeName) in groupedProducts" :key="storeName" class="store-group">
        <view class="store-name">{{ storeName }}</view>
        <view v-for="(product, index) in products" :key="index" class="product-item">
          <image class="product-img" :src="product.imgUrl" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <text class="product-sales">月售 {{ product.sales }} 件</text>
            <view class="price-section">
              <text class="price-current">¥{{ product.price }}</text>
              <text class="price-old">¥{{ product.oldPrice }}</text>
            </view>
            <text class="quantity-text">数量: {{ product.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 结算总价和提交订单按钮 -->
    <view class="checkout-footer">
      <view class="checkout-total">
        <text>结算总价: ¥{{ totalPrice }}</text>
      </view>
      <view class="submit-order-btn" @click="submitOrder">
        <text>提交订单</text>
      </view>
    </view>
  </view>
</template>

<script>
import config from "@/config.js";

export default {
  data() {
    return {
      receivedCartList: [],
      addressList: [],
      totalPrice: 0,
      stores: [],
      selectedAddress: {},
    };
  },
  onShow() {
    // 页面显示时检查是否有从地址页面返回的选中地址
    const selectedAddress = uni.getStorageSync('selectedAddress');
    if (selectedAddress) {
      this.selectedAddress = selectedAddress;
      uni.removeStorageSync('selectedAddress');
    }
  },
 computed: {
   groupedProducts() {
     if (!this.stores.length) return {};
     
     const grouped = {};
     this.receivedCartList.forEach(item => {
       const store = this.stores.find(s => 
         s._id === item.storeId || String(s._id) === String(item.storeId)
       );
       const storeName = store?.name || '未知超市';
       
       if (!grouped[storeName]) {
         grouped[storeName] = [];
       }
       grouped[storeName].push(item);
     });
     return grouped;
   }
 },
  onLoad(options) {
    if (options.cartList) {
      const cartListString = decodeURIComponent(options.cartList);
      this.receivedCartList = JSON.parse(cartListString);
      this.calculateTotalPrice();
    }
    this.fetchAddressList();
    this.fetchAllStores();
  },
  methods: {
    fetchAddressList() {
      uni.request({
        url: `${config.api_host}data`,
        success: (res) => {
          this.addressList = res.data;
          if (this.addressList.length > 0) {
            this.selectedAddress = this.addressList[0];
          }
        },
        fail: (error) => {
          console.error('获取收货地址列表出错:', error);
        }
      });
    },
  fetchAllStores() {
    uni.request({
      url: `${config.api_host}super`,
      success: (res) => {
        this.stores = res.data;
        console.log('获取到的店铺数据:', this.stores);
      },
      fail: (error) => {
        console.error('获取店铺信息出错:', error);
      }
    });
  },
    calculateTotalPrice() {
      this.totalPrice = this.receivedCartList.reduce(
        (acc, item) => acc + (item.quantity * item.price), 0
      ).toFixed(2);
    },
    getStoreName(storeId) {
      const store = this.stores.find(item => item._id === storeId);
      return store? store.name : '';
    },
    goToAddressPage() {
      uni.navigateTo({
        url: '/pages/me/meaddress?from=order'
      });
    },
    // 新增提交订单方法
    submitOrder() {
      uni.showModal({
        title: '确认支付',
        content: `您需要支付 ¥${this.totalPrice}，是否前往支付？`,
        success: (res) => {
          if (res.confirm) {
            const storeId = this.receivedCartList[0]?.storeId;
            // 获取当前时间并格式化
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hour = String(now.getHours()).padStart(2, '0');
            const minute = String(now.getMinutes()).padStart(2, '0');
            const orderTime = `${year}-${month}-${day} ${hour}:${minute}`; 

            const orderData = {
              address: this.selectedAddress,
              products: [...this.receivedCartList],
              totalPrice: this.totalPrice,
              storeId: storeId,
              orderTime: orderTime 
            };

            // 调用清空购物车方法
            if (storeId) {
              this.clearCheckedItems(storeId);
            }

            // 跳转到支付页面，并传递必要参数
            uni.navigateTo({
              url: `/pages/address/zf?price=${this.totalPrice}&storeName=${this.getStoreName(storeId)}&orderData=${encodeURIComponent(JSON.stringify(orderData))}`
            });
          }
        }
      });
    },
   clearCheckedItems(storeId) {
     try {
       // 1. 获取本地购物车数据
       const savedCart = wx.getStorageSync('cartList') || {};
       // 2. 如果有该店铺的购物车数据
       if (savedCart[storeId]) {
         // 3. 过滤掉已结算的商品（即receivedCartList中的商品）
         const remainingItems = savedCart[storeId].filter(cartItem => {
           return!this.receivedCartList.some(orderItem =>
             orderItem._id === cartItem._id
           );
         });
         // 4. 更新购物车数据
         if (remainingItems.length > 0) {
           savedCart[storeId] = remainingItems;
         } else {
           // 如果店铺购物车为空，则删除该店铺的购物车数据
           delete savedCart[storeId];
         }
         // 5. 保存回本地存储
         wx.setStorageSync('cartList', savedCart);
       }
     } catch (e) {
       console.error('清除已结算商品失败:', e);
     }
   }
  }
};
</script>

<style scoped>
.confirm-order-container {
  padding: 15px;
  background-color: #f8f8f8;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

/* 地址部分样式 */
.address-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.section-title {
  font-size: 16px;
  font-weight: bold;
  display: block;
  margin-bottom: 10px;
}
.address-info {
  font-size: 14px;
  line-height: 1.6;
}
.address-info text {
  display: block;
}

/* 商品部分样式 */
.product-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.store-group {
  margin-bottom: 15px;
}
.store-name {
  font-size: 15px;
  font-weight: bold;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
  color: #333;
}
.product-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px dashed #f0f0f0;
}
.product-item:last-child {
  border-bottom: none;
}
.product-img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 12px;
}
.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.product-name {
  font-size: 15px;
  color: #333;
  line-height: 1.4;
}
.product-sales {
  font-size: 12px;
  color: #999;
}
.price-section {
  display: flex;
  align-items: center;
  margin: 5px 0;
}
.price-current {
  font-size: 16px;
  color: #ff6700;
  font-weight: bold;
  margin-right: 8px;
}
.price-old {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}
.quantity-text {
  font-size: 14px;
  color: #666;
  align-self: flex-end;
}

/* 结算总价和提交订单按钮样式 */
.checkout-footer {
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
  background-color: #fff;
  padding: 12px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.05);
}

.checkout-total {
  font-size: 16px;
  font-weight: bold;
  color: #ff6700;
}

.submit-order-btn {
  background-color: #ff6700;
  padding: 8px 20px;
  border-radius: 4px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}
.edit-icon {
  width: 10px;
  height: 10px;
  float: right; /* 新增代码 */
  margin-top: -20px;
  margin-right: 10px;
}
</style>    